<?php
namespace CouchPHP;

/**
 * Default connection class for CouchPHP
 * Does not implement cache
 * @package CouchPHP
 * @author Jakub `Kofel` Kaflik
 */
class Connection
{
    /**
     * CouchDB server host
     * @var string
     */
    private $host;
    
    /**
     * CouchDB server port
     * @var int
     */
    private $port;
    
    /**
     * Optional authorization hash
     * @var string
     */
    private $authorizeHash;
    
    /**
     * Constructor
     * @param string $host
     * @param int $port 
     */
    public function __construct( $host, $port )
    {
        $this->host = $host;
        $this->port = $port;
    }
    
    /**
     * Creates authorization hash for further connections
     * @param string $username
     * @param string $password 
     */
    public function authorization( $username, $password )
    {
        $this->authorizeHash = base64_encode( $username . ':' . $password );
    }
    
    /**
     * Does REST request to CouchDB server
     * @param string $url
     * @param Request $type
     * @param mixed $data
     * @return Response 
     */
    public function doRequest( $url, $type = null, $data = null )
    {
        if( !$type )
            $type = Request::GET;
        
        $request = $type . " " . $url . " HTTP/1.0\r\nHost: " . $this->host . "\r\n";
        
        if( $this->authorizeHash )
        {
            $request .= "Authorization: Basic " . $this->authorizeHash . "\r\n";
        }
        
        if( $data )
        {
            $data = json_encode( $data );
            
            $request .= "Content-Length: " . strlen( $data ) . "\r\n";
            $request .= "Content-Type: application/json\r\n\r\n";
            $request .= $data;
        }
        
        $request .= "\r\n";

        $socket = @fsockopen( $this->host, $this->port, $err_num, $err_string, 2 );
        
        if( !$socket )
        {
            throw new ConnectionException("Socket timeout");
        }
        
        stream_set_timeout( $socket, 2 );
            
        fwrite( $socket, $request );
        
        $response = "";
        
        while( !feof( $socket ) )
        {
            $response .= fgets( $socket );
        }
        
        fclose( $socket );
        
        return new Response( $response );
    }
}